<template>

  <!--学科选择-->
  <el-tabs v-model="indexName">

    <el-tab-pane v-for="(subject,index) in arrangeStore.subjectList" :key="index" :label="subject.name"
                 :name="subject.code">
      <!--      <el-row>-->

      <div class="flex justify-around">
        <div @click="campusClick(subject.code,campus)" v-for="(campus) in Object.keys(arrangeData[subject.code])"
             :key="campus">
          <div class="text-xxl">
            {{ campusMap.get(campus) }}
          </div>

          <div class="flex justify-center">
            <div class="margin-right">
              总计:
              {{ arrangeAgg[subject.code][campus].total }}
            </div>
            <div>
              安排:
              {{ arrangeAgg[subject.code][campus].batch.total }}
            </div>
            <div>
              未安排:
              {{ arrangeAgg[subject.code][campus].dummyExamHall.total }}
            </div>
          </div>
        </div>
        <el-col @click="campusClick(subject.code)" :span="6">
          共计
          <div class="flex justify-center">
            <div>
              总计:
              {{ arrangeAgg[subject.code].total }}
            </div>
            <div>
              安排:
              {{ arrangeAgg[subject.code].arrangeNum }}
            </div>
            <div>

              未安排:
              {{ arrangeAgg[subject.code].unArrangeNum }}
            </div>
          </div>


        </el-col>

        <!--      </el-row>-->
      </div>
    </el-tab-pane>
  </el-tabs>


  <el-container>
    <el-aside width="250px">
      <div class="margin-top flex-direction justify-start align-start" style="width: 250px ">

        <div>
          已安排
          <!--          <div class="flex">-->
          <!--            <el-input placeholder="输入学号或姓名搜索">-->

          <!--            </el-input>-->

          <!--          </div>-->

        </div>
        <avue-tree :option="arrangeTreeOption"
                   :data="arrangeTreeData"
                   @node-click="nodeClick">

        </avue-tree>
        <el-button-group>
          <el-button>
            分配
            <text class="cuIcon-exit"></text>
          </el-button>
        </el-button-group>
        <div>
          未安排
          <div class="flex">
            <el-input v-model="unArrangeKeywords" placeholder="输入学号或姓名搜索">

            </el-input>

          </div>

        </div>
        <avue-tree :option="treeOption"
                   :data="unArrangeTreeData"
                   @node-click="nodeClick">
        </avue-tree>

      </div>
      <!--        <div class="flex-direction justify-between">-->
      <!--          <div class="margin">-->
      <!--            <el-button type="success">-->
      <!--              安排-->
      <!--              <div class="cuIcon-right"></div>-->
      <!--            </el-button>-->
      <!--          </div>-->

      <!--          <div class="margin">-->
      <!--            <el-button type="danger">-->
      <!--              <div class="cuIcon-back"></div>-->
      <!--              移除-->
      <!--            </el-button>-->
      <!--          </div>-->
      <!--        </div>-->


    </el-aside>
    <el-main>
      <avue-crud :option="option"
                 :data="data"
                 v-model:page="page"
                 v-model:search="search"
                 @search-change="searchChange"
                 @search-reset="resetChange"
                 @on-load="onLoad"
                 :height="208"
      >
        <template #menu="{size,row,index}">
          <el-button @click="arrangeBtnClick(row,index)"
                     icon="el-icon-check"
                     text
                     type="primary"
                     :size="size">调整
          </el-button>
        </template>
      </avue-crud>

    </el-main>
  </el-container>

  <!--弹窗-->
  <el-dialog
      v-model="dialogSetting.dialogShow"
      :title="dialogSetting.title"
      :width="dialogSetting.width"
      :before-close="handleClose"
  >


    <span>This is a message</span>

    <view v-if="dialogSetting.dialogMode==='adjustForm'">

      <avue-form :option="formOption"
                 v-model="formData"
      ></avue-form>

    </view>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogSetting.dialogShow = false">取消</el-button>
        <el-button type="primary" @click="hideDialog()">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {reactive, toRefs} from "vue";
import pinia from "@/store/store";
import {useArrangeStore} from "@/store/arrangeStore";
import {processAppConfig} from "@/util/appConfigUtil";
import _ from 'lodash'
import {batchConvert2List, buildBottomUnArrangeTree, buildLeftBatchTree, exchangeExamHall} from "@/util/arrange";
import {ElMessage} from 'element-plus'

const appConfig = processAppConfig()
const arrangeStore = useArrangeStore(pinia)
export default {
  name: "ArrangePreviewView",
  setup() {
    // arrangeStore.arrangeData = {}

    const topData = reactive({
      indexName: '',
      ...arrangeStore,
      campusMap: appConfig.columnDefines.campus.dicMap,
      dialogSetting: {
        dialogMode: 'adjustForm',
        dialogShow: false,
        title: '调整考场',
        width: '50%'
      }
    })

    const formData = reactive({
      formOption: {
        labelWidth: 120,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            prop: 'studentName',
            label: '姓名',
            span: 12,
            disabled: true,

          },
          {
            prop: 'studentId',
            label: '学号',
            span: 12,
            disabled: true,

          },
          {
            prop: 'subjectName',
            label: '学科',
            span: 12,
            disabled: true,
            type: 'select',
            dicData: appConfig.dicts.subjects
          },
          {
            prop: 'campus',
            label: '校区',
            span: 12,
            disabled: true,
            type: 'select',
            dicData: appConfig.dicts.campus
          },
          {
            prop: 'batchId',
            label: '批次',
            row: true,
            span: 24,
            type: 'select',
            dicData: []
          },
          {
            prop: 'examHallKey',
            label: '考场',
            row: true,
            span: 24,
            type: 'select',
            dicData: []
          }
        ]
      },
      formData: {
        fromBatchId: '',
        fromExamHallKey: '',
        fromIndex: 0
      }
    })
    const leftData = reactive({

      arrangeTreeOption: {
        multiple: true,
        filter: false,
        virtualize: true,
        defaultExpandAll: true,
        formOption: {},
        props: {
          labelText: '标题',
          label: 'label',
          value: 'value',
          children: 'children'
        }
      },
      arrangeTreeData: [
        {
          value: 0,
          label: '202考场',
          children: []
        },

      ],
      treeOption: {
        multiple: true,
        filter: false,
        virtualize: true,
        defaultExpandAll: true,
        formOption: {},
        props: {
          labelText: '标题',
          label: 'label',
          value: 'value',
          children: 'children'
        }
      },
      unArrangeTreeData: [
        {
          value: 0,
          label: '花津校区(88)',
          children: [
            {
              value: 1,
              label: '王其岩4343434320112001045',
            }
          ]
        },

      ],
      unArrangeKeywords: ""
    })
    const rightData = reactive({
      option: {
        // sortable: true,
        index: true,
        indexLabel: "序号",
        excelBtn: true,
        column: [
          {
            label: '学号',
            prop: 'studentId',
            type: 'input',
            search: true
          },
          {
            label: '姓名',
            prop: 'studentName',
            search: true
          },
          {
            label: '考场',
            prop: 'examHallName',
            type: 'input',


          },
          {
            label: '考场',
            prop: 'examHallKey',
            type: 'select',
            dicData: [],
            search: true,
            hide: true
          },
          {
            label: '批次',
            prop: 'batchId',
            type: 'input',
            search: true
          },

        ]
      },
      formOption: {
        column: [
          {
            label: '输入框',
            prop: 'input',
            type: 'input'
          },
          {
            label: '输入框',
            prop: 'input1'
          }
        ]
      },
      search: {},
      originData: [],
      filterData: [],
      pageData: [],
      page: {
        total: 1000,
        currentPage: 1,
        pageSize: 10
      },
      data: [],
    })

    function campusClick(subject, campus) {
      calcArrangeTableData(subject, campus)
    }

    function calcArrangeTableData(subject, campus) {
      var arrangeData = arrangeStore.arrangeData[subject];
      console.log('arrangeStore.arrangeData', arrangeStore.arrangeData)
      var obj = {}

      if (campus) {
        obj = arrangeData[campus];
        //已分配
        let data = batchConvert2List(obj.batch, campus)
        rightData.data = data;
        rightData.originData = data;
        rightData.filterData = data;
        subPage(rightData.data)
        leftData.arrangeTreeData = buildLeftBatchTree(obj.batch, campus)
        leftData.unArrangeTreeData = buildBottomUnArrangeTree(obj.dummyExamHall, campus)

      } else {
        leftData.unArrangeTreeData = []
        leftData.arrangeTreeData = []

        let data = []
        let arrangeDataClone = _.cloneDeep(arrangeData)
        for (let campusKey in arrangeDataClone) {
          let obj = arrangeDataClone[campusKey]
          var reduce = batchConvert2List(obj.batch, campusKey)

          data = data.concat(reduce)
          //计算未分配的
          leftData.unArrangeTreeData = leftData.unArrangeTreeData.concat(buildBottomUnArrangeTree(obj.dummyExamHall, campusKey))
          leftData.arrangeTreeData = leftData.arrangeTreeData.concat(buildLeftBatchTree(obj.batch, campusKey))

        }
        rightData.data = data;
        rightData.originData = data;
        subPage(rightData.data)
        rightData.filterData = data;
      }

      updateExamHallDicData(subject, campus)
    }

    //构建考场字典
    function buildExamHallDicData(subjectCode, campusCode) {
      let campus = appConfig.dicts.campus.find(item => item.value == campusCode)
      // let subject = appConfig.dicts.subjects.find(item => item.value == subjectCode)
      return appConfig.examHalls.filter(item => {
        let flag = item.campus == campusCode && item.open;
        if (item.subjects) {
          flag = flag && item.subjects.indexOf(subjectCode) >= 0
        }
        return flag;
      })
          .map(item => {
            return {
              label: `${campus.label}|${item.name}`,
              value: item.code
            }
          })
    }

    //构建批次字典
    function buildBatchDicData(subjectCode, campusCode) {

      console.log(leftData.arrangeTreeData)
      let arrangeTreeData = leftData.arrangeTreeData

      let campusTreeData = arrangeTreeData.find(item => item.value == campusCode)

      let children = campusTreeData.children
      if (children) {
        return children.map((item, index) => {
          return {
            label: item.label,
            value: index + 1,
            disabled: item.enough
          }
        })
      }
      return []
    }

    function onLoad(page) {
      let {pageSize, currentPage} = page
      rightData.page.currentPage = currentPage
      rightData.page.pageSize = pageSize


      subPage(rightData.filterData);
    }


    function subPage(data) {
      //分页
      console.log("分页", data)
      let {currentPage, pageSize, total} = rightData.page
      // if (pageSize !== this.page.pageSize) {
      if (data.length !== total || rightData.pageData.length > 0 && (rightData.pageData[0].length !== pageSize || rightData.pageData[0] !== data[0])) {
        rightData.pageData = _.chunk(data, pageSize)
      }
      rightData.page.total = data.length;
      rightData.data = rightData.pageData[currentPage - 1]
    }

    function nodeClick() {

    }

    const loadNode = (node, resolve) => {
      console.log(node, resolve)

    }

    //安排
    function arrangeBtnClick(row, index) {
      console.log(row, index)
      /**
       * batchId
       * :
       * 1
       * campus
       * :
       * 1
       * examHallKey
       * :
       * "2060403"
       * examHallName
       * :
       * "行知楼6号楼403"
       * major
       * :
       * "汉语言文学"
       * studentId
       * :
       * "22110101007"
       * studentName
       * :
       * "陈丽"
       * subjectCategory
       * :
       * "理工类"
       * subjectName
       * :
       * "0007110140"
       * teacherName
       * :
       * "卞维新"
       */

      formData.formData = {
        ...row,
        campus: String(row.campus),
        fromBatchId: row.batchId,
        fromExamHallKey: row.examHallKey,
        fromIndex: index
      }
      updateDicData(row.subjectName, row.campus)
      openDialog("adjustForm")
    }

    function openDialog(mode) {
      topData.dialogSetting.dialogShow = true;
      topData.dialogSetting.dialogMode = mode;
    }

    function hideDialog() {
      topData.dialogSetting.dialogShow = false;

      //调整考场
      if (topData.dialogSetting.dialogMode === 'adjustForm') {
        let data = formData.formData;
        let {batchId, fromBatchId, fromExamHallKey, fromIndex, examHallKey, subjectName, campus} = data;
        console.log(subjectName, campus)
        if (!(fromBatchId === batchId && fromExamHallKey === examHallKey)) {


          let arrangeData = arrangeStore.arrangeData[subjectName][campus]
          console.log(arrangeData)
          let toIndex = -1;
          let {
            msg,
            code
          } = exchangeExamHall(arrangeData, fromBatchId, fromExamHallKey, fromIndex, examHallKey, batchId, toIndex)
          console.log(msg, code)

          if (code === 0) {

            ElMessage({
              type: 'success',
              message: msg
            })
            //更新数据
            campusClick(subjectName, campus)
          } else {

            ElMessage({
              type: 'error',
              message: msg
            })
          }
        }

      }
    }


    function updateExamHallDicData(subjectCode, campusCode) {
      let examHallDicData = buildExamHallDicData(subjectCode, campusCode)
      let examHallKeyTableProp = rightData.option.column.find(item => item.prop === 'examHallKey')
      examHallKeyTableProp.dicData = examHallDicData;
    }

    //更新字典数据
    function updateDicData(subjectCode, campusCode) {
      //更新考场字典
      let examHallDicData = buildExamHallDicData(subjectCode, campusCode)
      let examHallKeyProp = formData.formOption.column.find(item => item.prop === 'examHallKey')
      examHallKeyProp.dicData = examHallDicData;

      //更新批次字典
      let batchDicData = buildBatchDicData(subjectCode, campusCode)
      let batchProp = formData.formOption.column.find(item => item.prop === 'batchId')
      batchProp.dicData = batchDicData;
    }

    function searchChange(params, done) {

      console.log(params)
      console.log('rightData.originData', rightData.originData)

      rightData.filterData = filterData(rightData.originData, params)
      subPage(rightData.filterData);
      done()
    }

    function resetChange() {
      rightData.filterData = rightData.originData;
      subPage(rightData.filterData);
    }


    //过滤数据
    function filterData(originData, params) {
      return originData.filter(item => {
        let flag = true;
        for (let paramsKey in params) {
          if (item[paramsKey] != undefined) {
            flag = flag && item[paramsKey] == params[paramsKey]
          }
        }
        return flag
      })
    }


    return {
      ...toRefs(leftData),
      ...toRefs(rightData),
      ...toRefs(topData),
      ...toRefs(formData),
      arrangeBtnClick,
      nodeClick,
      loadNode,
      arrangeStore,
      campusClick,
      subPage,
      onLoad,
      searchChange,
      resetChange,
      hideDialog

    }
  }
}
</script>

<style scoped>
@import "@/colorui/main.css";
</style>